﻿(function () {

    layui.use(["layer", "jquery", "form", "laydate"], function () {
        var layer = layui.layer;
        var $ = layui.jquery;
        var form = layui.form;
        var laydate = layui.laydate;
        var carousel = layui.carousel;

        $(document).ready(function () {
            loadOrder();
            $("#btn-Search").click(onSearchBtnClick);
        });

        var currentDate = moment().format("YYYY-MM-DD");
        if (moment().get("hours") < 15) {
            currentDate = moment().add(-1, "days").format("YYYY-MM-DD");
        }
        laydate.render({
            elem: '#txt-Search-Date',
            value: currentDate,
            isInitValue: true,
            showBottom: false
        });

        function onSearchBtnClick() {
            loadOrder();
        }

        function loadOrder() {
            $("#OrderList").html("");
            var loadingIndex = layer.msg(addStyle("正在加载 ......"),
                { icon: 16, shade: 0.01, offset: ["25%"], time: false });
            $.ajax("/ShopManage/Order/QueryByWhere", {
                method: "POST",
                data: getQueryParam(),
                complete: function (jqXHR, textStatus) {
                    layer.close(loadingIndex);
                },
                success: function (data, textStatus, jqXHR) {
                    if (data.Success == true) {
                        var data2 = data.Data;
                        if ($.isArray(data2)) {
                            handleData(data2);
                        }
                    }
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    layer.msg(addStyle("系统错误，请联系管理员！"),
                        { icon: 2, time: 3 * 1000, offset: ["25%"], closeBtn: true });
                }
            });

            function handleData(data) {
                var html = $("#OrderListTable").html();
                var count = 0;
                var sum = 0;
                data.forEach((item, i) => {
                    var html2 = html;
                    html2 = html2.replace("{{OrderNo}}", item["OrderNo"]);
                    html2 = html2.replace("{{ProductName}}", item["Name"]);
                    html2 = html2.replace("{{CreateTime}}", item["CreateTime"]);
                    html2 = html2.replace("{{Buyer}}", item["Buyer"]);
                    html2 = html2.replace("{{Seller}}", item["Seller"]);
                    html2 = html2.replace("{{Amount}}", item["Amount"]);
                    {
                        var state = item["State"];
                        var text = tool.getOrderStatusTextByValue(state);
                        var className = "";
                        if (state == tool.EOrderStatus.Unpaid) {
                            className = "order-state-notPaied";
                        } else if (state == tool.EOrderStatus.Paid) {
                            className = "order-state-paied";
                        } else if (state == tool.EOrderStatus.RecvPayment) {
                            className = "order-state-recv";
                        } else if (state == tool.EOrderStatus.Fetch) {
                            className = "order-state-recv";
                        }

                        var tmp = '<font class="' + className + '">' + text + '</font>';
                        html2 = html2.replace("{{State}}", tmp);
                    }
                    html2 = html2.replace("{{Visible}}", getVisibleText(item["Visible"]));
                    html2 = html2.replace("{{OrderId}}", item["Id"]);
                    html2 = html2.replace("{{PaymentVoucherImagePath}}", item["PaymentVoucherImagePath"]);
                    $("#OrderList").append(html2);
                    $(".view-Payment:last").click(onViewPaymentClick);
                    {
                        var hour = moment().get("hours");
                        var date = moment().format("YYYY-MM-DD");
                        var date2 = item["CreateTime"].substring(0, 10);
                        if (date == date2 && (hour >= 15 && hour <= 23)) {
                            $(".update-order:last").bind("click", item, onUpdateOrderClick);
                        } else {
                            $(".update-order:last").remove();
                        }
                    }
                    count++;
                    sum = sum.add(item["Amount"]);
                });
                $("#OrderStatistics-Count").text(count);
                $("#OrderStatistics-Sum").text(sum);
            }
        }

        function getQueryParam() {
            return {
                Date: $("#txt-Search-Date").val(),
                Buyer: $("#txt-Search-Buyer").val(),
                Seller: $("#txt-Search-Seller").val(),
                State: $("#sel-Search-OrderState").val(),
                OrderNo: $("#txt-Search-OrderNo").val()
            }
        }

        function getVisibleText(value) {
            if (value == 0) {
                return '<font class="not-release">未发布</font>';
            } else if (value == 1) {
                return '<font class="released">已发布</font>';
            }
        }

        function onViewPaymentClick() {
            var el = $(this);
            var paths = el.attr("paymentPaths");

            layer.open({
                type: 1,
                title: "满堂创品",
                shade: [0.5, '#000'],
                skin: 'layui-layer-molv',
                offset: "5%",
                area: ["90%", "90%"],
                resize: false,
                content: '<div id="ViewPaymentDlg2">' + $("#ViewPaymentDlg").html() + '</div>'
            });

            if (paths != null && paths != "") {
                var el = $("#ViewPaymentDlg2 > div").eq(0);
                var el2 = $("#ViewPaymentDlg2 > div > div").eq(0);
                var width = $("#ViewPaymentDlg2").parent().width();
                var height = $("#ViewPaymentDlg2").parent().height();
                var html = '';
                var arr = paths.split(",");
                arr.forEach(item => {
                    var src = item;
                    html += '<div><img style="width: ' + width + 'px; height: ' + height + 'px;" src=" ' + src + '"></div>';

                });
                if (arr != null && arr.length > 0) {
                    el2.append(html);
                    carousel.render({
                        elem: el,
                        width: width + "px",
                        height: height + "px",
                        interval: 3000
                    });
                }
            }
        }

        function onUpdateOrderClick(event) {
            var data = event.data;
            var orderId = data["Id"];
            var buyerUserId = data["BuyerUserId"];
            var sellerUserId = data["SellerUserId"];

            var layId = layer.open({
                type: 1,
                title: "满堂创品",
                shade: [0.5, '#000'],
                skin: 'layui-layer-molv',
                offset: "10%",
                area: ["90%", "280px"],
                resize: false,
                content: '<div id="UpdateOrderDlg2">' + $("#UpdateOrderDlg").html() + '</div>'
            });

            form.render($("#txt-UpdateOrderDlg-Amount"));
            $("#lb-UpdateOrderDlg-OrderNo").text(data["OrderNo"]);
            $("#lb-UpdateOrderDlg-Buyer").text(data["Buyer"]);
            $("#lb-UpdateOrderDlg-Seller").text(data["Seller"]);
            $("#txt-UpdateOrderDlg-Amount").val(data["Amount"]);
            $("#btn-UpdateOrderDlg-UpdateBuyer").bind("click", onUpdateBuyerClick)
            $("#btn-UpdateOrderDlg-UpdateSeller").bind("click", onUpdateSellerClick)
            $("#btn-UpdateOrderDlg-OK").click(onUpdateOrderDlgOKClick);

            function onUpdateBuyerClick(event) {
                showSelectUserDlg(function (userId, name) {
                    buyerUserId = userId;
                    $("#lb-UpdateOrderDlg-Buyer").text(name);
                });
            }

            function onUpdateSellerClick(event) {
                showSelectUserDlg(function (userId, name) {
                    sellerUserId = userId;
                    $("#lb-UpdateOrderDlg-Seller").text(name);
                });
            }

            function onUpdateOrderDlgOKClick() {
                var amount = $("#txt-UpdateOrderDlg-Amount").val();
                if (!(amount >= 1000 && amount <= 15000)) {
                    layer.msg("订单金额不正确！");
                    return;
                }
                if (buyerUserId == sellerUserId) {
                    layer.msg("买家和卖家不可以相同！");
                    return;
                }

                layer.confirm(addStyle("确定要修改订单信息码？"), { icon: 3 }, function () {
                    var loadingIndex = layer.msg(addStyle("正在处理 ......"),
                        { icon: 16, shade: 0.01, offset: ["25%"], time: false });
                    $.ajax("/ShopManage/Order/UpdateOrder", {
                        method: "POST",
                        data: {
                            OrderId: orderId,
                            Amount: amount,
                            BuyerUserId: buyerUserId,
                            SellerUserId: sellerUserId
                        },
                        complete: function (jqXHR, textStatus) {
                            layer.close(loadingIndex);
                        },
                        success: function (data, textStatus, jqXHR) {
                            if (data.Success == true) {
                                layer.close(layId);
                                layer.msg(addStyle("更新订单成功！"));
                                loadOrder();
                            } else {
                                layer.msg(addStyle("更新订单失败： " + data.Msg));
                            }
                        },
                        error: function (XMLHttpRequest, textStatus, errorThrown) {
                            layer.msg(addStyle("系统错误，请联系管理员！"),
                                { icon: 2, time: 3 * 1000, offset: ["25%"], closeBtn: true });
                        }
                    });
                });
            }
        }

        function showSelectUserDlg(fn) {
            var userId = 0;
            var name = "";

            var layId = layer.open({
                type: 1,
                title: "满堂创品",
                shade: [0.5, '#000'],
                skin: 'layui-layer-molv',
                offset: "10%",
                area: ["90%", "450px"],
                resize: false,
                content: '<div id="SelectUserDlg2">' + $("#SelectUserDlg").html() + '</div>'
            });

            $("#btn-SelectUserDlg-OK").click(onSelectUserDlgOKClick);
            $("#btn-SelectUserDlg-Search").click(onSelectUserDlgSearchClick);

            var loadingIndex = layer.msg(addStyle("正在加载 ......"),
                { icon: 16, shade: 0.01, offset: ["25%"], time: false });
            $.ajax("/ShopManage/User/QueryShopAllUsers", {
                method: "POST",
                complete: function (jqXHR, textStatus) {
                    layer.close(loadingIndex);
                },
                success: function (data, textStatus, jqXHR) {
                    if (data.Success == true) {
                        var data2 = data.Data;
                        if ($.isArray(data2)) {
                            handleData(data2);
                        }
                    }
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    layer.msg(addStyle("系统错误，请联系管理员！"),
                        { icon: 2, time: 3 * 1000, offset: ["25%"], closeBtn: true });
                }
            });

            function handleData(data) {
                var html = '';
                data.forEach(item => {
                    html += '<label tagUserId="' + item["UserId"] + '" tagPhone="' + item["Phone"] + '">' + item["Name"] + '</label>';
                });
                $("#SelectUserDlg-UserList").append(html);
                $("#SelectUserDlg-UserList label").click(onUserLabelClick);
            }

            function onUserLabelClick() {
                var el = $(this);
                userId = parseInt(el.attr("tagUserId"), 10);
                name = el.text();
                var text = el.text() + " - " + el.attr("tagPhone");
                $("#lb-SelectUserDlg-Name2").text(text);
            }

            function onSelectUserDlgOKClick() {
                if (userId == 0) {
                    layer.msg(addStyle("请选择用户！"));
                } else {
                    layer.close(layId);
                    if (fn != null) {
                        fn(userId, name);
                    }
                }
            }

            function onSelectUserDlgSearchClick() {
                var els = $("#SelectUserDlg-UserList label");
                var text = $("#txt-SelectUserDlg-Name").val();
                for (var i = 0; i < els.length; i++) {
                    var item = els.eq(i);
                    if (item.text().indexOf(text) > -1) {
                        item.show();
                    } else {
                        item.hide();
                    }
                }
            }
        }

        function addStyle(str) {
            return '<span style="font-size: 16px;">' + str + '</span>';
        }
    });

})();